<script setup lang="ts">
import { getDebuggerWebSocketAPI } from '@/api/gateway'
import { WebSocketPlus } from '@utils/websocket/WebSocketPlus'
import { useDeviceStatusStore } from '@/dataset/device-status/store'
import { toEditPageCheck } from '@/utils'
import { computed } from 'vue'

const props = withDefaults(defineProps<{
  // 网关id
  id?: string,
  name?: string,
  updateOnlineStatus?: boolean,
  showTemplatesDialog(): void,
  closeTemplatesDialog(): void
}>(), {
  updateOnlineStatus: true
})

const emits = defineEmits(['templatesChange', 'update:modelValue'])

onMounted(() => {
  props.id && openDebugger()
})

// region TODO 在线状态
const deviceStatusStore = useDeviceStatusStore()
onMounted(() => {
  props.updateOnlineStatus && deviceStatusStore.startUpdateStatus()
})
onActivated(() => {
  props.updateOnlineStatus && deviceStatusStore.startUpdateStatus()
})

onDeactivated(() => {
  props.updateOnlineStatus && deviceStatusStore.stopUpdateStatus()
})

onBeforeUnmount(() => {
  props.updateOnlineStatus && deviceStatusStore.stopUpdateStatus()
})
// endregion

// region TODO 调试
const debuggingJSON = shallowRef<any>({ tip: '请选择网关进行调试' })
const debuggerWs = shallowRef<WebSocketPlus>()
const isConnected = shallowRef(false)
function openDebugger () {
  debuggerWs.value = getDebuggerWebSocketAPI({ gatewayId: props.id })
  debuggingJSON.value = { tip: '等待推送数据，请稍等...' }
  debuggerWs.value.onMessage((res) => {
    try {
      if (res.data) { debuggingJSON.value = JSON.parse(res.data) }
    } catch (e) {

    }
  }).onState((ev) => {
    isConnected.value = ev.connect
  })
}
function closeDebugger () {
  if (debuggerWs.value) {
    debuggerWs.value.close()
    debuggerWs.value = null
  }
  debuggingJSON.value = {}
}
watch(() => props.id, () => {
  closeDebugger()
  if (props.id) {
    openDebugger()
    props.closeTemplatesDialog()
  }
})

let _isConnected = false
onActivated(() => {
  if (_isConnected) {
    debuggerWs.value && debuggerWs.value.open()
  }
})

onDeactivated(() => {
  _isConnected = isConnected.value
  debuggerWs.value && debuggerWs.value.close()
})
onUnmounted(() => {
  closeDebugger()
})
// endregion

// region TODO 生成变量模板
// 可用模板
type templatesType = { id: string, address: string[], name: string }
const templates = computed<templatesType[]>(() => {
  const ret = []
  const devices = debuggingJSON.value.devices
  if (devices && Array.isArray(devices)) {
    devices.forEach(device => {
      if (device.deviceId && device.deviceData) {
        try {
          const keys = Object.keys(device.deviceData)
          if (keys.length) {
            ret.push({ id: device.deviceId, address: keys, name: props.name + device.deviceId })
          }
        } catch (e) {
        }
      }
    })
  }
  emits('templatesChange', ret)
  return ret
})
// endregion

</script>

<template>
  <div class="debugging d-flex flex-column">
    <div v-if="props.id" class="d-flex justify-content-between bor-success-b pb-1">
      <div class="d-flex align-items-center">
        <div style="height: 6px;aspect-ratio: 1;border-radius: 50%;" :class="isConnected ? 'bg-color-success' : 'bg-color-danger'" />
        <template v-if="props.name">
          <div class="ml-1">调试网关：</div>
          <span>{{ props.name }}</span>
        </template>
        <div class="ml-3">状态：</div>
        <span>{{ deviceStatusStore.gatewaysStatus[props.id] ? '在线' : '离线' }}</span>
      </div>
      <div>
        <el-button size="small" plain type="success" @click="isConnected ? debuggerWs.close() : debuggerWs.open()">
          {{ isConnected ? '断开': '连接' }}
        </el-button>
        <el-button
          v-if="templates.length" size="small" plain
          type="success"
          @click="props.showTemplatesDialog"
        >
          生成变量模板
        </el-button>
      </div>
    </div>
    <div class="flex-1">
      <div class="position-relative wh-100 overflow-auto">
        <pre class="wh-100 position-absolute"><code>{{ debuggingJSON }}</code></pre>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
// 表格 - 设备列表
.debugging {
  background-color: #0C0C0C;
  color: var(--el-color-success);
  //max-height: calc(100% - 45px);
  overflow: auto;
  padding: 18px 32px;
}

</style>
